package com.sxjh.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.handler.AbstractUrlHandlerMapping;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请求路径对应的方法
 */
@Configuration
public class RequestUrlMap {

  @Autowired
  private WebApplicationContext applicationContext;

  private List<Map<String, String>> list = new ArrayList<>();;

  public void init() {
    // 获取springmvc处理器映射器组件对象 RequestMappingHandlerMapping无法直接注入
    RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
    //获取url与类和方法的对应信息
    Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
    for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
      Map<String, String> one = new HashMap<String, String>();
      RequestMappingInfo info = m.getKey();
      HandlerMethod method = m.getValue();
      // 获取url
      PatternsRequestCondition p = info.getPatternsCondition();
      for (String url : p.getPatterns()) {
          one.put("url", url);
      }
      // 反射获取url对应类名和方法名
      one.put("className", method.getMethod().getDeclaringClass().getName()); // 类名
      one.put("method", method.getMethod().getName()); // 方法名
      // 获取请求类型
      RequestMethodsRequestCondition methodsRequestCondition = info.getMethodsCondition();
      for (RequestMethod requestMethod : methodsRequestCondition.getMethods()) {
        one.put("type", requestMethod.toString());
      }
      list.add(one);
    }
  }


  /**
   *
   * @param url 请求路径
   * @param type 请求方式
   * @return
   */
  public Method getMethod(String url, String type) {
    if (list.size() == 0) init();
    for (Map<String, String> map : list) {
      RequestMappingHandlerMapping requestMappingHandlerMapping = new RequestMappingHandlerMapping();
//      requestMappingHandlerMapping.match()
//      HandlerMapping
//      AbstractUrlHandlerMapping
      String url2 = map.get("url");
      if (!url.equals(url2)) continue;
      String type2 = map.get("type");
      if (!type.equals(type2)) continue;
//      System.out.println(map.get("className"));
//      System.out.println(map.get("method"));
    }
    return null;
  }

}
